import {
  queryAreaInfo,
  getAreaShape,
  getAreaType,
  addArea,
  editArea,
  removeArea,
} from '../services/api';
import { message } from 'antd';
export default {
  namespace: 'areaInfo',

  state: {
    list: [],
    pagination: {
      current: 1,
      pageSize: 10,
    },
    typeCodes: [],
    shapeCodes: [],
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryAreaInfo, payload);
      let dataSource = response.adThrowInAreas;
      if (dataSource) {
        const result = {
          list: Array.isArray(response.adThrowInAreas) ? dataSource : [],
        };

        //console.log('log', result);
        yield put({
          type: 'save',
          payload: result,
        });
      }
    },
    *fetchType({ payload }, { call, put }) {
      const response = yield call(getAreaType, payload);
      // console.log('response', response);
      yield put({
        type: 'savetype',
        payload: {
          list: Array.isArray(response.adTiAreaTypeCodes) ? response.adTiAreaTypeCodes : [],
        },
      });
    },
    *fetchShape({ payload }, { call, put }) {
      const response = yield call(getAreaShape, payload);
      // console.log('response', response);
      yield put({
        type: 'saveshape',
        payload: {
          list: Array.isArray(response.adTiAreaShapeCodes) ? response.adTiAreaShapeCodes : [],
        },
      });
    },
    *add({ payload, callback }, { call, put }) {
      const response = yield call(addArea, payload);
      if (response?.result?.code !== 1000) {
        message.error('添加区域出错，请检查');
      } else {
        if (callback) callback();
      }
    },
    *edit({ payload, callback }, { call, put }) {
      const response = yield call(editArea, payload);
      if (response?.result?.code !== 1000) {
        message.error('编辑区域出错，请检查');
      } else {
        if (callback) callback();
      }
    },

    *remove({ payload, callback }, { call, put }) {
      const response = yield call(removeArea, payload);
      if (response?.result?.code !== 1000) {
        message.error(response.result.msg);
      } else {
        yield put({
          type: 'removeArea',
          payload,
        });
        if (callback) callback();
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        list: action.payload.list,
        pagination: action.payload.pagination,
      };
    },
    saveshape(state, action) {
      return {
        ...state,
        shapeCodes: action.payload.list,
      };
    },
    savetype(state, action) {
      return {
        ...state,
        typeCodes: action.payload.list,
      };
    },
    removeArea(state, action) {
      const newlist = state.list.filter(item => item.areaId != action.payload.areaId);
      return {
        ...state,
        list: newlist,
      };
    },
  },
};
